﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CSConsoleTest
{
    class TestTask : BaseConsoleTest
    {
        public void printDescription()
        {
            Console.WriteLine("--- Task ---");
        }

        public void doTest()
        {
            //Method 1 : ASYNC
            Action taskAction = () => 
            {
                Thread.Sleep(1000);
                Console.WriteLine("Task done");
            };

            Task task1 = new Task(taskAction);
            task1.Start();
            Console.WriteLine("Task start asynchronously");
            task1.Wait();

            //Method 2 : ASYNC
            var task2 = Task.Factory.StartNew(
                () =>
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("Task done");
                }
            );
            Console.WriteLine("Task start asynchronously");
            task2.Wait();

            //Method 3 : SYNC
            Console.WriteLine("Task start synchronously");
            Task task3 = new Task(taskAction);
            task3.RunSynchronously();

            task3.Wait();

            //Method 4 : ASYNC : Return result
            Console.WriteLine("Task start asynchronously and has result");
            Func<object, List<int>> testFunc = (paramRangeObj) =>
                {
                    List<int> testList = new List<int>();

                    IntRange rangeObj = paramRangeObj as IntRange;

                    if (rangeObj.Start > rangeObj.End)
                    {
                        return testList;
                    }

                    for (int num = rangeObj.Start; num <= rangeObj.End; num++)
                    {
                        testList.Add(num);
                    }

                    return testList;
                };

            Task<List<int>> test4 = new Task<List<int>>(testFunc, (new IntRange() { Start = 1, End = 10 }));
            test4.Start();
            test4.Wait();
            Console.WriteLine("Task start asynchronously. below is result list.");
            
            List<int> resultList = test4.Result;
            foreach(int result in resultList)
            {
                Console.Write("{0}, ", result);
            }
            Console.WriteLine();
            
        }
    }

    class IntRange
    {
        public int Start { set; get; }
        public int End { set; get; }
    }
}
